package com.cruise.game.service.impl.common;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cruise.game.common.api.ApiException;
import com.cruise.game.mapper.ChatMapper;
import com.cruise.game.mapper.UserMapper;
import com.cruise.game.model.entity.Chat;
import com.cruise.game.model.entity.User;
import com.cruise.game.model.vo.chat.ChatMessageVO;
import com.cruise.game.model.vo.common.PageResult;
import com.cruise.game.service.common.ChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 聊天服务实现
 *
 * @author cruise
 * @date 2025-02-28
 */
@Slf4j
@Service
public class ChatServiceImpl implements ChatService {

    @Resource
    private ChatMapper chatMapper;

    @Resource
    private UserMapper userMapper;

    @Override
    public Long sendMessage(Long userId, Long adminId, String message, boolean isFromUser) {
        // 验证用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new ApiException("用户不存在");
        }

        // 验证管理员是否存在
        User admin = userMapper.selectById(adminId);
        if (admin == null || !"admin".equals(admin.getRole())) {
            throw new ApiException("管理员不存在");
        }

        // 创建聊天记录
        Chat chat = new Chat();
        chat.setUserId(userId);
        chat.setAdminId(adminId);
        chat.setMessage(message);
        chat.setIsFromUser(isFromUser);
        chat.setCreatedAt(LocalDateTime.now());

        chatMapper.insert(chat);

        return chat.getId();
    }

    @Override
    public PageResult<ChatMessageVO> getChatHistory(Long userId, Integer page, Integer pageSize) {
        // 查询聊天历史
        IPage<Chat> chatPage = chatMapper.selectUserChatHistory(new Page<>(page, pageSize), userId);

        // 转换为VO
        List<ChatMessageVO> chatMessageVOs = chatPage.getRecords().stream()
                .map(this::convertToChatMessageVO)
                .collect(Collectors.toList());

        return PageResult.of(chatMessageVOs, chatPage.getTotal(), page, pageSize);
    }

    @Override
    public PageResult<ChatMessageVO> getChatHistoryWithAdmin(Long userId, Long adminId, Integer page,
            Integer pageSize) {
        // 查询聊天历史
        IPage<Chat> chatPage = chatMapper.selectUserAdminChatHistory(
                new Page<>(page, pageSize), userId, adminId);

        // 转换为VO
        List<ChatMessageVO> chatMessageVOs = chatPage.getRecords().stream()
                .map(this::convertToChatMessageVO)
                .collect(Collectors.toList());

        return PageResult.of(chatMessageVOs, chatPage.getTotal(), page, pageSize);
    }

    @Override
    public List<ChatMessageVO> getNewMessages(Long userId, Long adminId, LocalDateTime afterTime) {
        // 查询新消息
        List<Chat> chats = chatMapper.selectChatAfterTime(userId, adminId, afterTime);

        // 转换为VO
        return chats.stream()
                .map(this::convertToChatMessageVO)
                .collect(Collectors.toList());
    }

    @Override
    public int getUnreadMessageCount(Long userId, LocalDateTime lastReadTime) {
        return chatMapper.countUnreadMessages(userId, lastReadTime);
    }

    @Override
    public Long findAdminUser() {
        // 查找角色为admin的第一个用户
        User adminUser = userMapper.selectFirstAdminUser();
        return adminUser != null ? adminUser.getId() : null;
    }

    /**
     * 转换为聊天消息VO
     */
    private ChatMessageVO convertToChatMessageVO(Chat chat) {
        ChatMessageVO vo = new ChatMessageVO();
        BeanUtils.copyProperties(chat, vo);
        return vo;
    }
}